package org.zookeeper.study;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

/** 
* @author James
* @date 2018年8月16日 
*/
public class MyZookeeper implements Watcher{

	protected CountDownLatch countDownLatch=new CountDownLatch(1);
	
	private static final int SESSION_TIME=2000;
	
	public static ZooKeeper zookeeper=null; 
	
	/**
	 * 监控所有被触发的事件
	 */
	@Override
	public void process(WatchedEvent event) {
		System.out.println("收到事件通知："+event.getState());
		if(event.getState()==KeeperState.SyncConnected) {
			countDownLatch.countDown();
		}
	}
	
	public void connect(String hosts) {
		try {
			if(zookeeper==null) {
				zookeeper=new ZooKeeper(hosts,SESSION_TIME,this);
				countDownLatch.await();	
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		if(zookeeper!=null) {
			try {
				zookeeper.close();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}
